<template>
  <div class="app-container question">
    <el-form :model="queryParam" ref="queryForm" :inline="true"  style="text-align: center;">
      <el-row>
        <el-form-item label="题干内容包含：">
          <el-input v-model="queryParam.textContentKeyword" clearable></el-input>
        </el-form-item>
        <el-form-item label="题目分类：">
          <el-autocomplete
            v-model="queryParam.category"
            class="inline-input"
            :fetch-suggestions="querySearch0"
            placeholder="请选择（或输入）题目分类"
            style="cursor: pointer"
            @keyup.native="fuzzyqueryJob($event,input)"
          >
            <template slot-scope="{ item }">
                <a :title="item.value" style="text-decoration:none">{{ item.value }}</a>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="题型：">
          <el-select v-model="queryParam.questionType" clearable>
            <el-option v-for="item in questionType" :key="item.key" :value="item.key" :label="item.value"
              :title="item.value">
              <span>{{ item.value }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-form-item>
        <el-button type="info" @click="resetForm" style="margin-right: 12px">重置</el-button>
        <el-popover placement="bottom" trigger="click">
          <el-button type="success" size="mini" v-for="item in editUrlEnum" :key="item.key"
          @click="$router.push({path:item.value})">{{item.name}}
        </el-button>
        <el-button slot="reference" type="success" class="link-left">添加题目</el-button>
        </el-popover>
        <el-button type="primary" @click="submitForm" style="margin-left: 12px">查询</el-button>
      </el-form-item>
    </el-form>
    <el-form :inline="true" style="text-align: center; display:  flex; flex-direction: column; justify-content: center; align-items: center;">
      <el-table v-loading="listLoading" :data="tableData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="id" label="Id" width="60px"/>
        <el-table-column prop="category" label="分类" width="120px"/>
        <el-table-column prop="questionType" label="题型" :formatter="questionTypeFormatter" width="100px">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.questionType == 1">单选题</el-tag>
            <el-tag type="primary"  v-if="scope.row.questionType == 2">多选题</el-tag>
            <el-tag type="danger"  v-if="scope.row.questionType == 3">判断题</el-tag>
            <el-tag type="warning"  v-if="scope.row.questionType == 4">填空题</el-tag>
            <el-tag type="info"  v-if="scope.row.questionType == 5">简答题</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="shortTitle" label="题干" show-overflow-tooltip/>
        <el-table-column prop="score" label="分数" width="60px"/>
        <el-table-column prop="difficult" label="难度" width="60px"/>
        <el-table-column prop="createTime" label="创建时间" width="160px"/>
        <el-table-column label="操作" align="center" width="220px">
          <template slot-scope="{row}">
            <el-button size="mini" type="primary"  @click="showQuestion(row)">预览</el-button>
            <el-button size="mini" type="success" style="margin-left: 5px;" @click="editQuestion(row)">编辑</el-button>
            <el-popconfirm
              title="确定删除该记录吗？"
              @confirm="deleteQuestion(row)">
              <el-button size="mini"  type="danger" slot="reference" class="link-left">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="queryParam.pageIndex" :limit.sync="queryParam.pageSize"
                  @pagination="search"/>
    </el-form>
    <el-dialog :visible.sync="questionShow.dialog" style="width: 100%;height: 100%">
      <QuestionShow :qType="questionShow.qType" :question="questionShow.question" :qLoading="questionShow.loading"/>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapState, mapActions } from 'vuex'
import Pagination from '@/components/Pagination'
import QuestionShow from './components/Show'
import questionApi from '@/api/question'

export default {
  components: { Pagination, QuestionShow },
  data () {
    return {
      questionCategoryList: [],
      queryParam: {
        id: undefined,
        questionType: undefined,
        category: undefined,
        score: undefined,
        difficult: undefined,
        startTime: undefined,
        endTime: undefined,
        pageIndex: 1,
        pageSize: 10
      },
      subjectFilter: null,
      listLoading: true,
      tableData: [],
      total: 0,
      questionShow: {
        qType: 0,
        dialog: false,
        question: null,
        loading: false
      }
    }
  },
  created () {
    this.loaadAll()
    this.initSubject()
    this.search()
  },
  methods: {
    resetForm() {
      this.queryParam = {
        id: undefined,
        questionType: undefined,
        category: undefined,
        score: undefined,
        difficult: undefined,
        startTime: undefined,
        endTime: undefined,
        pageIndex: 1,
        pageSize: 10
      }
      this.search()
    },
    fuzzyqueryJob(e, input) {
      if (this.queryParam.category !== '' && this.queryParam.category !== null && this.queryParam.category !== undefined) {
        const jobParam = { keyword: this.queryParam.category + '' }
        questionApi.questionCategory(jobParam).then(res => {
          this.questionCategoryList = res.response
        })
      }
    },
    createFilter(queryString) {
      return returnJobs => {
        return (
          returnJobs.toLowerCase().indexOf(queryString.toLowerCase()) !== -1 // 改为===0 就是筛选的数据只是首字匹配的列表项，需要包含输入字的所有列表项改为！==-1
        )
      }
    },
    querySearch0(queryString, cb) {
      const categorylist = this.questionCategoryList
      let results = queryString
        ? categorylist.filter(this.createFilter(queryString))
        : categorylist
      results = results.map(item => {
        return {
          value: item
        }
      })
      cb(results)
    },
    loaadAll() {
      questionApi.questionCategory().then(res => {
        this.questionCategoryList = res.response
      })
    },
    submitForm () {
      this.queryParam.pageIndex = 1
      this.search()
    },
    search () {
      this.listLoading = true
      questionApi.pageList(this.queryParam).then(data => {
        const re = data.response
        this.tableData = re.list
        this.total = re.total
        this.queryParam.pageIndex = re.pageNum
        this.listLoading = false
      })
    },
    levelChange () {
      this.queryParam.subjectId = null
      this.subjectFilter = this.subjects.filter(data => data.level === this.queryParam.level)
    },
    addQuestion () {
      this.$router.push('/question-bank/question/edit/singleChoice')
    },
    showQuestion (row) {
      let _this = this
      this.questionShow.dialog = true
      this.questionShow.loading = true
      questionApi.select(row.id).then(re => {
        _this.questionShow.qType = re.response.questionType
        _this.questionShow.question = re.response
        _this.questionShow.loading = false
      })
    },
    editQuestion (row) {
      let url = this.enumFormat(this.editUrlEnum, row.questionType)
      this.$router.push({ path: url, query: { id: row.id } })
    },
    deleteQuestion (row) {
      let _this = this
      questionApi.deleteQuestion(row.id).then(re => {
        if (re.code === 1) {
          _this.search()
          _this.$message.success(re.message)
        } else {
          _this.$message.error(re.message)
        }
      })
    },
    questionTypeFormatter (row, column, cellValue, index) {
      return this.enumFormat(this.questionType, cellValue)
    },
    subjectFormatter (row, column, cellValue, index) {
      return this.subjectEnumFormat(cellValue)
    },
    ...mapActions('exam', { initSubject: 'initSubject' })
  },
  computed: {
    ...mapGetters('enumItem', ['enumFormat']),
    ...mapState('enumItem', {
      questionType: state => state.exam.question.typeEnum,
      editUrlEnum: state => state.exam.question.editUrlEnum,
      levelEnum: state => state.user.levelEnum
    }),
    ...mapGetters('exam', ['subjectEnumFormat']),
    ...mapState('exam', { subjects: state => state.subjects })
  }
}
</script>

<style rel="stylesheet/scss" lang='scss'>
  .question .el-form-item--medium .el-form-item__label {
    line-height: 36px;
    margin-left: 15px;
  }


  .question .el-form-item__error {
    color: #ff4949;
    font-size: 12px;
    line-height: 1;
    padding-top: 0px;
    position: absolute;
    top: 100%;
    left: 0;
  }

  .question .pagination-container {
    margin-top: 18px;
    margin-bottom: 18px;
  }
  
  .question .cell .el-tag {
    margin-right: 0px;
    width: 88%;
    text-align: center;
  }

  .question .el-table .cell {
    text-align: center;
  }
  </style>
